//
//  FCWalletTransactionDetailVC.m
//  FundChain
//
//  Created by 肖浩然的mac on 2018/3/1.
//  Copyright © 2018年 RUIXIN. All rights reserved.
//

#import "FCWalletTransactionDetailVC.h"
#import "FCBottomTransactionhistoryCell.h"
#import "FCTransactionHistoryVC.h"
#import "FCSendAndReceiveVC.h"
#import "FCMJRefreshFooter.h"
#import "FCMJRefreshHeader.h"
@interface FCWalletTransactionDetailVC ()<UITableViewDataSource,UITableViewDelegate>{
    UIView *_viewNav;
    UIImageView *_imageViewDismiss;
    UIView *_bgView;
    UILabel *_tipsLabel;
    UIButton *_btn;
    UIButton *_refreshbtn;
}
/* viewLine */
@property (strong, nonatomic) UIView *viewLine;
@property (strong, nonatomic) UITableView *tableView;
/* 交易记录 */
@property (strong, nonatomic) FCTransactionHistoryDetailModel * transactionHistoryDetailModel;

/* title */
@property (strong, nonatomic)  UILabel *backLabel;
/** 当前页 */
@property(nonatomic, assign) NSUInteger currentPage;
/* 交易记录模型 */
@property (strong, nonatomic) FCTransactionHistoryModel *transactionHistoryModel;
/* 交易详情数据源 */
@property (strong, nonatomic) NSMutableArray *orderArr;
@end

@implementation FCWalletTransactionDetailVC


- (void)viewDidLoad {
    [super viewDidLoad];
    [FCLocalUserHelper saveIsMainVC:@"0"];
    [self setNav];
    [self setupUI];
    [self refresh];
    [self addSendAndReceive];
    [self addDismissImage];
}
-(void)addDismissImage{
    
    UIView *bgView = [UIView new];
    _bgView = bgView;
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
         make.top.mas_equalTo(64);
         make.left.mas_equalTo(0);
         make.right.mas_equalTo(0);
         make.bottom.mas_equalTo(-96*KScreenHeightScale1334);
    }];
    bgView.backgroundColor = kClearColor;
    bgView.hidden =YES;
    _imageViewDismiss =[UIImageView new];
    [bgView addSubview:_imageViewDismiss];
    [_imageViewDismiss mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(114*KScreenHeightScale1334);
        make.centerX.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(160, 160));
    }];
    [_imageViewDismiss setBackgroundColor:[UIColor clearColor]];
    [_imageViewDismiss setImage:[UIImage imageNamed:@"img_data"]];
    
    //提示
    UILabel *tipsLabel = [UILabel new];
    _tipsLabel = tipsLabel;
    [bgView addSubview:tipsLabel];
    [tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_imageViewDismiss.mas_bottom).offset(50);;
        make.centerX.mas_equalTo(0);
    }];
    tipsLabel.textColor = kGrayColor;
    //btn
    UIButton *btn = [UIButton new];
    _btn = btn;
    [bgView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(tipsLabel.mas_bottom).offset(10);
        make.centerX.mas_equalTo(0);
    }];
    [btn setTitle:Localized(@"返回") forState:UIControlStateNormal];
    [btn setTitleColor:kRedOrangeColor forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    //刷新
    UIButton *refreshbtn = [UIButton new];
    _refreshbtn = refreshbtn;
    [bgView addSubview:refreshbtn];
    [refreshbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(tipsLabel.mas_bottom).offset(10);
        make.centerX.mas_equalTo(0);
    }];
    [refreshbtn setTitle:Localized(@"刷新") forState:UIControlStateNormal];
    [refreshbtn setTitleColor:kRedOrangeColor forState:UIControlStateNormal];
    [refreshbtn addTarget:self action:@selector(refreshbtnClick) forControlEvents:UIControlEventTouchUpInside];
    refreshbtn.hidden = YES;
    UIView *viewLine =[UIView new];
    [bgView addSubview:viewLine];
    [viewLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(btn);
        make.top.mas_equalTo(btn.mas_bottom).offset(-2);
        make.height.mas_equalTo(1);
    }];
    viewLine.backgroundColor =kRedOrangeColor;

}
#pragma mark-UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
     FCTransactionHistoryDetailModel *detailModel = self.orderArr[indexPath.row];
    FCTransactionHistoryVC *vc = [FCTransactionHistoryVC new];
    vc.transactionHistoryDetailModel = detailModel;
    vc.currentResultModel = self.currentResultModel;
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark-UItableViewdatasouce
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 160*KScreenHeightScale1334;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.orderArr.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    FCBottomTransactionhistoryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"bottomCell"];
    cell = [[FCBottomTransactionhistoryCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"bottomCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    _transactionHistoryDetailModel= self.orderArr[indexPath.row];
    cell.transactionHistoryDetailModel = _transactionHistoryDetailModel;
    if (self.orderArr.count>0) {
        
        FCTransactionHistoryDetailModel *model = self.orderArr[0];
        NSRange range =NSMakeRange(0, 10);
        NSString * aString = [FCLocalUserHelper getBabyDetailAge:model.sendTime];
        NSString * string = [aString substringWithRange:range];
        NSMutableArray * muArray=[[NSMutableArray    alloc]initWithCapacity:0];
        
        NSString * str ;
        for (int i = 0 ;i<self.orderArr.count;i++) {
            
            FCTransactionHistoryDetailModel *model1 = self.orderArr[i];
            NSString * bString = [FCLocalUserHelper getBabyDetailAge:model1.sendTime];
            str = [bString substringWithRange:range];
            
            if (![string isEqualToString:str]) {
                model1.sameTime = @"1";
                [muArray addObject:self.orderArr[i]];
                string = str;
            }
        }
        
        
        if ([_transactionHistoryDetailModel.sameTime isEqualToString:@"1"]) {
            cell.monthLabel.hidden = NO;
        }else if(indexPath.row == 0){
            cell.monthLabel.hidden = NO;
        }else{
            cell.monthLabel.hidden = YES;
        }
        
    }
    
    
    return cell;
}
#pragma mark-设置UI
-(void)setupUI{
    //bottomTitle
    UIView *bottomTitleView = [UIView new];
    [self.view addSubview:bottomTitleView];
    [bottomTitleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_viewNav.mas_bottom);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(100*KScreenHeightScale1334);
    }];
    bottomTitleView.backgroundColor = kWhiteColor;
    //title
    UILabel *titleLabel = [UILabel new];
    [bottomTitleView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(30*KScreenWidthScale750);
        make.centerY.mas_equalTo(0);
    }];
    titleLabel.text = Localized(@"交易历史");
    titleLabel.font = Kfont(32);
    //分割线
    UIView *viewLine =[UIView new];
    self.viewLine = viewLine;
    [self.view addSubview:viewLine];
    [viewLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(bottomTitleView.mas_bottom);
        make.height.mas_equalTo(1);
    }];
    viewLine.backgroundColor =kLineColor;
    
    //添加tableView
    [self tableView];
    
}
#pragma mark-tableView
//懒加载tableView
-(UITableView*)tableView{
    
    if(!_tableView)
    {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView ];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.viewLine.mas_bottom);
            make.left.mas_offset(0);
            make.right.mas_offset(0);
            make.bottom.mas_offset(0);
        }];
        _tableView.showsHorizontalScrollIndicator = YES;
        _tableView.backgroundColor = kWhiteColor;
        [_tableView setSeparatorStyle:(UITableViewCellSeparatorStyleNone)];
        //        _tableView.tableFooterView = [UIView new];
    }
    return _tableView;
}
#pragma mark-自定义导航栏
-(void)setNav{
    self.navigationController.navigationBarHidden = YES;
    _viewNav =[UIView new];
    [self.view addSubview:_viewNav];
    [_viewNav mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            if (iPhoneX) {
                
                make.left.right.top.mas_equalTo(self.view.safeAreaInsets);
                make.height.mas_equalTo(88);
            }else{
                make.left.right.mas_equalTo(0);
                make.height.mas_equalTo(64);
                make.top.mas_equalTo(0);
            }
        }else{
            make.left.right.mas_equalTo(0);
            make.height.mas_equalTo(64);
            make.top.mas_equalTo(0);
        }
        
    }];
    _viewNav.backgroundColor = kRedOrangeColor;
    
    UIButton *leftBtn = [UIButton new];
    [self.view addSubview:leftBtn];
    [leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15*KScreenWidthScale750);
        make.centerY.mas_equalTo(_viewNav.mas_centerY).offset(8);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    [leftBtn setImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
    [leftBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    //返回
    UILabel *backLabel = [UILabel new];
    self.backLabel = backLabel;
    [_viewNav addSubview:backLabel];
    [backLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(_viewNav);
        make.centerY.mas_equalTo(_viewNav.mas_centerY).offset(8);
    }];
    backLabel.textColor = [UIColor whiteColor];
    backLabel.font = KOverstrikingfont(36);
    switch ([self.walletId integerValue]) {
        case 1001:
        {
            self.backLabel.text = Localized(@"比特币");
        }
            break;
        case 1005:
        {
            self.backLabel.text = Localized(@"莱特币");
        }
            break;
        case 1006:
        {
            self.backLabel.text = Localized(@"比特币现金");
        }
            break;
        case 1009:
        {
            self.backLabel.text = Localized(@"加密现金币");
        }
            break;
        case 1010:
        {
            self.backLabel.text = Localized(@"零币");
        }
            break;
            
        default:
            break;
    }
    //事件
    [leftBtn addTarget:self action:@selector(leftBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
}
-(void)addSendAndReceive{
    
    UIView *bottomView = [UIView new];
    [self.view addSubview: bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.mas_equalTo(0);
        make.height.mas_equalTo(96*KScreenHeightScale1334);
    }];
    //头部分割线
    UIView *topViewLine =[UIView new];
    [bottomView addSubview:topViewLine];
    [topViewLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.height.mas_equalTo(1);
        make.right.mas_equalTo(0);
    }];
    topViewLine.backgroundColor =kLineColor;
    //    bottomView.backgroundColor = [UIColor redColor];
    //send按钮
    JMBaseButtonConfig *buttonConfig = [JMBaseButtonConfig buttonConfig];
    buttonConfig.title = Localized(@"发送");
    buttonConfig.titleFont = Kfont(36);
    buttonConfig.titleColor = kwarningColor;
    buttonConfig.image = [UIImage imageNamed:@"Send"];
    buttonConfig.styleType = JMButtonStyleTypeLeft;
    JMButton *btn = [[JMButton alloc] initWithFrame:CGRectMake(0, 1, SCREEN_WIDTH/2-1, 50) ButtonConfig:buttonConfig];
    [btn addTarget:self action:@selector(sendBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:btn];
    //分割线
    UIView *viewLine =[UIView new];
    [bottomView addSubview:viewLine];
    [viewLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(btn.mas_right);
        make.centerY.mas_equalTo(0);
        make.height.mas_equalTo(56*KScreenHeightScale1334);
        make.width.mas_equalTo(1);
    }];
    viewLine.backgroundColor =kLineColor;
    
    UIView *viewLine1 =[UIView new];
    [bottomView insertSubview:viewLine1 belowSubview:viewLine];
    [viewLine1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(btn.mas_right);
        make.top.mas_equalTo(1);
        make.centerY.mas_equalTo(0);
        make.height.mas_equalTo(95*KScreenHeightScale1334);
        make.width.mas_equalTo(5);
    }];
    viewLine1.backgroundColor =[UIColor whiteColor];
    //receive
    JMBaseButtonConfig *buttonConfig2 = [JMBaseButtonConfig buttonConfig];
    buttonConfig2.title = Localized(@"接收");
    buttonConfig2.titleFont = Kfont(36);
    buttonConfig2.titleColor = kgreenassistColor;
    buttonConfig2.image = [UIImage imageNamed:@"receive"];
    buttonConfig2.styleType = JMButtonStyleTypeLeft;
    JMButton *btn2 = [[JMButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2+1, 1, SCREEN_WIDTH/2-1, 50) ButtonConfig:buttonConfig2];
    [btn2 addTarget:self action:@selector(receiveBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:btn2];
}
-(void)sendBtnClick{
  
    FCSendAndReceiveVC *sendAndReceiveVC = [FCSendAndReceiveVC new];
    sendAndReceiveVC.selectIndex = 0;
    sendAndReceiveVC.walletId = self.walletId;
    sendAndReceiveVC.currentResultModel = self.currentResultModel;
    [self.navigationController pushViewController:sendAndReceiveVC animated:YES];

}
//刷新
- (void)refresh{
    
    
    
    __weak typeof(self) weakSelf = self;
    FCMJRefreshHeader *header = [FCMJRefreshHeader headerWithRefreshingBlock:^{
        
        weakSelf.currentPage = 1;
        
        [weakSelf postTransactionHistoryMessageWith:self.walletId];
        
    }];
    
    weakSelf.tableView.mj_header = header;
    weakSelf.tableView.mj_footer = [FCMJRefreshFooter footerWithRefreshingBlock:^{
        weakSelf.currentPage++;
        [weakSelf postTransactionHistoryMessageWith:self.walletId];
        
    }];

        [self.tableView.mj_header beginRefreshing];
   
    
}

-(void)receiveBtnClick{
    
     FCSendAndReceiveVC *sendAndReceiveVC = [FCSendAndReceiveVC new];
    sendAndReceiveVC.selectIndex = 1;
    sendAndReceiveVC.walletId = self.walletId;
    sendAndReceiveVC.currentResultModel = self.currentResultModel;
    [self.navigationController pushViewController:sendAndReceiveVC animated:YES];
}
-(void)backClick{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)refreshbtnClick{
    [self refresh];
}
-(void)leftBtnClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark-获取交易记录
-(void)postTransactionHistoryMessageWith:(NSString*)walletId{
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:1];
    NSArray *signArr = [FCLocalUserHelper getTimeAndSign];
    NSString *signStr = [NSString stringWithFormat:@"%@",signArr[1]];
    NSString *timeStr = [NSString stringWithFormat:@"%@",signArr[0]];
    [dict setObject:[FCLocalUserHelper sha1:signStr] forKey:@"sign"];
    [dict setObject:timeStr forKey:@"time"];
    [dict setObject:[FCLocalUserHelper getXidStr] forKey:@"XID"];
    [dict setObject:walletId forKey:@"walletId"];
    [dict setObject:[NSString stringWithFormat:@"%zd",self.currentPage] forKey:@"page"];
    NSString *url = Get_wallet_histroy_URL;
    __weak __typeof(self)wself = self;
    
    [FCSharedNetworkTool POSTWithURLString:url parameters:dict success:^(id responseObject) {
        if (responseObject) {
            NSLog(@"%@",responseObject);
            if ([responseObject[@"code"] integerValue] == 200) {
                
                _transactionHistoryModel = [FCTransactionHistoryModel mj_objectWithKeyValues:responseObject[@"result"]];
                
                if (!kArrayIsEmpty(_transactionHistoryModel.orders) ) {
                    
                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                        
                        NSArray *orderArr = _transactionHistoryModel.orders;
                        Language Language = [CLanguageUtil getCurrentLanguage];
                        //                        NSString * getTimeFormatIDStr = [FCLocalUserHelper getTimeFormatIDStr];
                        NSMutableArray *arrM = [NSMutableArray new];
                        [orderArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                            
                            FCTransactionHistoryDetailModel *detailModel = [FCTransactionHistoryDetailModel mj_objectWithKeyValues:obj];
                            NSString * sendTime = detailModel.sendTime;
                            switch (Language) {
                                case Language_Hans: case Language_Hant:
                                {
                                    detailModel.sendData = [FCLocalUserHelper changetimeIntervalChineseData:sendTime];
                                    
                                }
                                    break;
                                case Language_EN:
                                {
                                    detailModel.sendData = [FCLocalUserHelper changetimeIntervalData:sendTime];
                                }
                                    break;
                                default:
                                    break;
                            }
                            [arrM addObject:detailModel];
                            [wself.orderArr addObject:detailModel];
                        }];
                        
                        if (self.currentPage ==1) {
                            wself.orderArr = arrM;
                        }else if(self.currentPage >1)
                        {
                            
                            for (int i =0 ; i<arrM.count; i++) {
                                FCTransactionHistoryDetailModel *model= arrM[i];
                                [wself.orderArr addObject:model];
                            }
                            
                        }
                        
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                            [wself.tableView.mj_header endRefreshing];
                            [wself.tableView.mj_footer endRefreshing];
                            [self.tableView reloadData];
                        });
                    });
                    _bgView.hidden = YES;
                    
                }else{
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        [self.tableView reloadData];
                        [wself.tableView.mj_header endRefreshing];
                        [wself.tableView.mj_footer endRefreshingWithNoMoreData];
                    });
                    if ([responseObject[@"result"][@"nowpage"]  isEqual: @"1"]) {
                        _refreshbtn.hidden = YES;
                        _tipsLabel.hidden = NO;
                        [_imageViewDismiss setImage:[UIImage imageNamed:@"img_data"]];
                        _bgView.hidden = NO;
                        _tipsLabel.text = Localized(@"还没有数据");
                        [self.view bringSubviewToFront:_bgView];
                    }
                   
                    
                }
            }
            
            
        }
        
    } faile:^(NSError *error) {
        if (error) {
            NSLog(@"%@",error);
        }
        _imageViewDismiss.image= [UIImage imageNamed:@"img_network"];
        _bgView.hidden = NO;
        _btn.hidden = YES;
        _refreshbtn.hidden = NO;
        _tipsLabel.text = Localized(@"网络连接失败");
        [self.view bringSubviewToFront:_bgView];
        [wself.tableView.mj_header endRefreshing];
        [wself.tableView.mj_footer endRefreshing];
        wself.currentPage--;
    }];
    
    
}
#pragma mark-懒加载
-(NSMutableArray *)orderArr{
    if (!_orderArr) {
        _orderArr = [NSMutableArray new];
    }
    return _orderArr;
}
@end
